package com.fangcang.mongodb.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import com.fangcang.mongodb.impl.MongoDbApiService;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;

//@Configuration
//@PropertySource("classpath:mongodb.properties")
public class MongoApiConfiguration {
	
	@Value("${mongodb.host}")
	private String host;
	@Value("${mongodb.port}")
	private int port;
	@Value("${mongodb.dbName}")
	private String dbName;
	@Value("${mongodb.userName}")
	private String userName;
	@Value("${mongodb.collectionName}")
	private String collectionName;
	@Value("${mongodb.password}")
	private String password;
	
	@Bean
	public MongoConfig mongoConfig() {
		MongoConfig mongoConfig = new MongoConfig();
		mongoConfig.setHost(host);
		mongoConfig.setPort(port);
		mongoConfig.setUserName(userName);
		mongoConfig.setPassword(password);
		mongoConfig.setCollectionName(collectionName);
		mongoConfig.setDbName(dbName);
		return mongoConfig;
	}

	@Bean
	public MongoClient mongoClient() {
		ServerAddress serverAddress = new ServerAddress(host, port);
		return new MongoClient(serverAddress);
	}
	
	
	@Bean
	public MongoDatabase mongoDatabase() {
		return mongoClient().getDatabase(dbName);
	}
	
	@Bean
	public MongoDbApiService mongoDbApiService(MongoClient mongoClient, MongoDatabase mongoDatabase, MongoConfig mongoConfig) {
		MongoDbApiService mongoDbService = new MongoDbApiService(mongoConfig);
		return mongoDbService;
	}
}
